package main

import (
	"encoding/json"
	"log"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"time"

	"net/smtp"

	"github.com/joho/godotenv"
)

type EmailData struct {
	FormHtml string `json:"formHtml"`
}

func main() {
	// 加载.env文件中的环境变量
	err := godotenv.Load()
	if err != nil {
		log.Fatalf("加载.env文件时出错,检查是否配置环境信息：%v", err)
	}

	// 设置静态文件目录
	staticDir := http.Dir("public")
	staticHandler := http.StripPrefix("/public/", http.FileServer(staticDir))

	// 为静态文件创建一个路由
	http.Handle("/public/", staticHandler)

	// 设置HTML页面路由
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "public/index.html")
	})

	http.HandleFunc("/api/send", sendForm)

	port := os.Getenv("PORT")
	// 如果PORT环境变量为空，则使用默认端口9998
	if port == "" {
		port = "9998"
	}
	// 自动打开浏览器
	openBrowser("http://localhost:" + port)

	log.Fatal(http.ListenAndServe(":"+port, nil))
}

func sendForm(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Redirect(w, r, "/", http.StatusSeeOther)
		return
	}

	var data EmailData
	err := json.NewDecoder(r.Body).Decode(&data)
	if err != nil {
		http.Error(w, "JSON正文解码出错", http.StatusBadRequest)
		return
	}

	formTitle := os.Getenv("FORM_TITLE")
	// 发送邮件
	err = SendMail(formTitle, data.FormHtml)
	if err != nil {
		http.Error(w, "提交失败", http.StatusInternalServerError)
		log.Println(err)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Write([]byte(`{"success": true, "message": "提交成功!"}`))

	// 重定向到成功页面
	go successHandler()

}

// SendMail 使用提供的邮件主题和正文发送邮件
func SendMail(subject string, body string) error {
	// 从环境变量中读取配置
	smtpUser := os.Getenv("SMTP_USER")
	smtpPassword := os.Getenv("SMTP_PASSWORD")
	fromEmail := os.Getenv("FROM_EMAIL")
	toEmail := os.Getenv("TO_EMAIL")

	// 发送邮件
	auth := smtp.PlainAuth("", smtpUser, smtpPassword, "smtp.qq.com")
	to := []string{toEmail}

	// 注意：邮件头和邮件体需要用CRLF作为分隔符
	msg := "From: " + fromEmail + "\r\n" +
		"To: " + strings.Join(to, ",") + "\r\n" +
		"Subject: " + subject + "\r\n" +
		"MIME-Version: 1.0\r\n" +
		"Content-Type: text/html; charset=\"utf-8\"\r\n\r\n" +
		body

	return smtp.SendMail("smtp.qq.com:587", auth, fromEmail, to, []byte(msg))
}

// openBrowser 函数接受一个url作为参数，打开默认的浏览器访问该url
func openBrowser(url string) {
	var cmd *exec.Cmd
	var err error

	if os.Getenv("GOOS") == "windows" {
		cmd = exec.Command(`cmd`, `/c`, `start`, url)
	} else {
		browser := os.Getenv("BROWSER")
		log.Println("BROWSER:", browser)
		if browser == "" || browser == "default" {
			cmd = exec.Command(`open`, url)
		} else {
			cmd = exec.Command(`xdg-open`, url)
		}
	}

	if err = cmd.Start(); err != nil {
		log.Fatalf("Failed to open browser: %v", err)
	}
}

// 成功处理函数
func successHandler() {
	// 提交成功后关闭服务器
	time.Sleep(2 * time.Second)
	log.Println("服务关闭中...")
	os.Exit(0)
}
